<script setup lang="ts">
import type {
  EnergyDataReportList,
  ReportColumnsItem,
} from '../types'
import WrapComponent from './WrapComponent.vue'
import TableHead from './TableHead.vue'
import ReportPerson from './ReportPerson.vue'
import { getFlatternColumns } from './util'

import useInformant from './useInformant'
import useReportCell from './useReportCell'
import useArrowKey from './useArrowKey'
import { uuid } from '@/utils'
import { energyMetrologicalReviewApi } from '@/api'

const props = defineProps<{
  dataTime: string
  readonly?: boolean
}>()
const title = ref('能源计量器具准确度等级统计汇总表')
const columns: ReportColumnsItem[] = [
  { label: '计量器具类别', prop: 'A' },
  { label: '计量目的', prop: 'B', colspan: 2 },
  {
    label: '进出用能单位',
    prop: 'C',
    children: [
      {
        label: '准确度等级要求',
        prop: 'accuracyClassAsk1',
      },
      {
        label: '实际准确度等级',
        prop: 'realityAccuracyClass1',
      },
    ],
  },
  {
    label: '进出主要次级用能单位',
    prop: 'D',
    children: [
      {
        label: '准确度等级要求',
        prop: 'accuracyClassAsk2',
      },
      {
        label: '实际准确度等级',
        prop: 'realityAccuracyClass2',
      },
    ],
  },
  {
    label: '主要用能设备',
    prop: 'E',
    children: [
      {
        label: '准确度等级要求',
        prop: 'accuracyClassAsk3',
      },
      {
        label: '实际准确度等级',
        prop: 'realityAccuracyClass3',
      },
    ],
  },
  {
    label: '其他项目',
    prop: 'F',
    children: [
      {
        label: '准确度等级要求',
        prop: 'accuracyClassAsk4',
      },
      {
        label: '实际准确度等级',
        prop: 'realityAccuracyClass4',
      },
    ],
  },
]
/** 从第三列开始 */
const flatternColumns = getFlatternColumns(
  columns.slice(2),
)

/** 衡器 */
const lists1 = ref<
  (EnergyDataReportList & { measurementPurpose: number })[]
    >([
      ...[1, 2].map(v => ({
        uuid: uuid('temp_'),
        measurementPurpose: v,
        data: [
          ...flatternColumns.map(v => ({
            key: v.prop,
            value: '',
            editable: !props.readonly,
          })),
        ],
      })),
    ])

/** 电能表 */
const lists2 = ref<
  (EnergyDataReportList & { measurementPurpose: number })[]
    >([
      ...[3, 4, 5, 6, 7, 8].map(v => ({
        uuid: uuid('temp_'),
        measurementPurpose: v,
        data: [
          ...flatternColumns.map(v => ({
            key: v.prop,
            value: '',
            editable: !props.readonly,
          })),
        ],
      })),
    ])

/** 油流量表（装置） */
const lists3 = ref<
  (EnergyDataReportList & { measurementPurpose: number })[]
    >([
      ...[9, 10].map(v => ({
        uuid: uuid('temp_'),
        measurementPurpose: v,
        data: [
          ...flatternColumns.map(v => ({
            key: v.prop,
            value: '',
            editable: !props.readonly,
          })),
        ],
      })),
    ])

/** 气体流量表（装置） */
const lists4 = ref<
  (EnergyDataReportList & { measurementPurpose: number })[]
    >([
      ...[11].map(v => ({
        uuid: uuid('temp_'),
        measurementPurpose: v,
        data: [
          ...flatternColumns.map(v => ({
            key: v.prop,
            value: '',
            editable: !props.readonly,
          })),
        ],
      })),
    ])

/** 水流量表（装置） */
const lists5 = ref<
  (EnergyDataReportList & { measurementPurpose: number })[]
    >([
      ...[12, 13].map(v => ({
        uuid: uuid('temp_'),
        measurementPurpose: v,
        data: [
          ...flatternColumns.map(v => ({
            key: v.prop,
            value: '',
            editable: !props.readonly,
          })),
        ],
      })),
    ])

/** 温度仪表 */
const lists6 = ref<
  (EnergyDataReportList & { measurementPurpose: number })[]
    >([
      ...[14, 15].map(v => ({
        uuid: uuid('temp_'),
        measurementPurpose: v,
        data: [
          ...flatternColumns.map(v => ({
            key: v.prop,
            value: '',
            editable: !props.readonly,
          })),
        ],
      })),
    ])

/** 压力仪表 */
const lists7 = ref<
  (EnergyDataReportList & { measurementPurpose: number })[]
    >([
      ...[16, 17].map(v => ({
        uuid: uuid('temp_'),
        measurementPurpose: v,
        data: [
          ...flatternColumns.map(v => ({
            key: v.prop,
            value: '',
            editable: !props.readonly,
          })),
        ],
      })),
    ])

const { informant, setInformant } = useInformant()

const loading = ref(false)
function findLists(
  data: any[],
  measurementPurpose: number,
) {
  const target = data.find(
    v => +v.measurementPurpose === measurementPurpose,
  )
  return {
    uuid: target ? `${target.id}` : uuid('temp_'),
    measurementPurpose,
    data: [
      ...flatternColumns.map(v => ({
        key: v.prop,
        value: target ? target[v.prop] : '',
        editable: !props.readonly,
      })),
    ],
  }
}
async function loadList() {
  loading.value = true
  try {
    const { data }
      = await energyMetrologicalReviewApi.selectToolsAccuracyClass(
        props.dataTime,
      )

    const informantData = data.find((v: any) => +v.type === 2)
    informantData && setInformant(informantData)

    lists1.value = [findLists(data, 1), findLists(data, 2)]
    lists2.value = [
      findLists(data, 3),
      findLists(data, 4),
      findLists(data, 5),
      findLists(data, 6),
      findLists(data, 7),
      findLists(data, 8),
    ]
    lists3.value = [
      findLists(data, 9),
      findLists(data, 10),
    ]
    lists4.value = [findLists(data, 11)]
    lists5.value = [
      findLists(data, 12),
      findLists(data, 13),
    ]
    lists6.value = [
      findLists(data, 14),
      findLists(data, 15),
    ]
    lists7.value = [
      findLists(data, 16),
      findLists(data, 17),
    ]
  }
  finally {
    loading.value = false
  }
}

const dataTime = toValue(props.dataTime) || (`${new Date().getFullYear()}`)
function resolveLists(lists: Ref<(EnergyDataReportList & { measurementPurpose: number })[]>) {
  const listsValue = toValue(lists)
  return listsValue.map(v => ({
    id: Number(v.uuid) || undefined,
    type: 1,
    measurementPurpose: v.measurementPurpose,
    dataTime,
    ...v.data.reduce((acc, vv) => {
      acc[vv.key] = vv.value
      return acc
    }, {}),
  }))
}
async function saveStage() {
  const list = [
    ...resolveLists(lists1),
    ...resolveLists(lists2),
    ...resolveLists(lists3),
    ...resolveLists(lists4),
    ...resolveLists(lists5),
    ...resolveLists(lists6),
    ...resolveLists(lists7),
  ]

  /** 填报人信息 */
  list.push({
    type: 2,
    dataTime,
    ...toValue(informant),
  })

  await energyMetrologicalReviewApi.saveOrUpdateToolsAccuracyClass(
    list,
  )
}

const { inputIndex, initInputIndex, clickCallback }
  = useReportCell()
useArrowKey(inputIndex, flatternColumns.length)

onMounted(async () => {
  await loadList()
  initInputIndex()
})
</script>

<template>
  <WrapComponent>
    <template v-if="$slots.title" #title>
      <slot
        name="title"
        :title="title"
        :save-stage="saveStage"
      />
    </template>
    <div
      v-loading="loading"
      class="width-fill height-fill flex-direction flex"
    >
      <div class="report-table-head">
        <table class="report-table">
          <TableHead
            :columns="columns"
            :show-line-number="false"
          />
        </table>
      </div>
      <ElScrollbar>
        <table class="report-table" style="height: auto">
          <tbody ref="tbody">
            <!-- 衡器 -->
            <tr
              v-for="(item, i) in lists1"
              :key="item.uuid"
            >
              <td v-if="i === 0" :rowspan="lists1.length">
                <div class="span-cell">
                  衡器
                </div>
              </td>
              <td v-if="i === 0" colspan="2">
                <div class="span-cell">
                  燃料的静态计量
                </div>
              </td>
              <td v-if="i === 1" colspan="2">
                <div class="span-cell">
                  燃料的动态计量
                </div>
              </td>
              <td
                v-for="(d, index) in item.data"
                :key="`${item.uuid}_${index}`"
              >
                <div v-if="!d.editable" class="span-cell">
                  {{ d.value }}
                </div>
                <div v-else class="input-cell">
                  <input
                    v-model="d.value"
                    type="text"
                    @click="clickCallback"
                  >
                </div>
              </td>
            </tr>

            <!-- 电能表 -->
            <tr
              v-for="(item, i) in lists2"
              :key="item.uuid"
            >
              <td v-if="i === 0" :rowspan="lists2.length">
                <div class="span-cell">
                  电能表
                </div>
              </td>
              <td
                v-if="i === 0"
                :rowspan="lists2.length - 1"
              >
                <div class="span-cell">
                  有功交流电能计量
                </div>
              </td>
              <td v-if="i === 0">
                <div class="span-cell">
                  Ⅰ 类用户
                </div>
              </td>
              <td v-if="i === 1">
                <div class="span-cell">
                  Ⅱ 类用户
                </div>
              </td>
              <td v-if="i === 2">
                <div class="span-cell">
                  Ⅲ 类用户
                </div>
              </td>
              <td v-if="i === 3">
                <div class="span-cell">
                  Ⅳ 类用户
                </div>
              </td>
              <td v-if="i === 4">
                <div class="span-cell">
                  Ⅴ 类用户
                </div>
              </td>
              <td v-if="i === 5" colspan="2">
                <div class="span-cell">
                  直流电能计量
                </div>
              </td>

              <td
                v-for="(d, index) in item.data"
                :key="`${item.uuid}_${index}`"
              >
                <div v-if="!d.editable" class="span-cell">
                  {{ d.value }}
                </div>
                <div v-else class="input-cell">
                  <input
                    v-model="d.value"
                    type="text"
                    @click="clickCallback"
                  >
                </div>
              </td>
            </tr>

            <!-- 油流量表（装置） -->
            <tr
              v-for="(item, i) in lists3"
              :key="item.uuid"
            >
              <td v-if="i === 0" :rowspan="lists3.length">
                <div class="span-cell">
                  油流量表（装置）
                </div>
              </td>
              <td
                v-if="i === 0"
                :rowspan="lists3.length"
                colspan="2"
              >
                <div class="span-cell">
                  液体能源计量
                </div>
              </td>
              <td
                v-for="(d, index) in item.data"
                :key="`${item.uuid}_${index}`"
              >
                <div v-if="!d.editable" class="span-cell">
                  {{ d.value }}
                </div>
                <div v-else class="input-cell">
                  <input
                    v-model="d.value"
                    type="text"
                    @click="clickCallback"
                  >
                </div>
              </td>
            </tr>

            <!-- 气体流量表（装置） -->
            <tr
              v-for="(item, i) in lists4"
              :key="item.uuid"
            >
              <td v-if="i === 0" :rowspan="lists4.length">
                <div class="span-cell">
                  气体流量表（装置）
                </div>
              </td>
              <td
                v-if="i === 0"
                :rowspan="lists4.length"
                colspan="2"
              >
                <div class="span-cell">
                  气体能源计量
                </div>
              </td>
              <td
                v-for="(d, index) in item.data"
                :key="`${item.uuid}_${index}`"
              >
                <div v-if="!d.editable" class="span-cell">
                  {{ d.value }}
                </div>
                <div v-else class="input-cell">
                  <input
                    v-model="d.value"
                    type="text"
                    @click="clickCallback"
                  >
                </div>
              </td>
            </tr>

            <!-- 水流量表（装置） -->
            <tr
              v-for="(item, i) in lists5"
              :key="item.uuid"
            >
              <td v-if="i === 0" :rowspan="lists5.length">
                <div class="span-cell">
                  水流量表（装置）
                </div>
              </td>
              <td v-if="i === 0" :rowspan="lists5.length">
                <div class="span-cell">
                  水流量计量
                </div>
              </td>
              <td v-if="i === 0">
                <div class="span-cell">
                  管径不大于 250 mm
                </div>
              </td>
              <td v-if="i === 1">
                <div class="span-cell">
                  管径大于 250 mm
                </div>
              </td>
              <td
                v-for="(d, index) in item.data"
                :key="`${item.uuid}_${index}`"
              >
                <div v-if="!d.editable" class="span-cell">
                  {{ d.value }}
                </div>
                <div v-else class="input-cell">
                  <input
                    v-model="d.value"
                    type="text"
                    @click="clickCallback"
                  >
                </div>
              </td>
            </tr>

            <!-- 温度仪表 -->
            <tr
              v-for="(item, i) in lists6"
              :key="item.uuid"
            >
              <td v-if="i === 0" :rowspan="lists6.length">
                <div class="span-cell">
                  温度仪表
                </div>
              </td>
              <td v-if="i === 0" colspan="2">
                <div class="span-cell">
                  用于液态、气态能源的温度计算
                </div>
              </td>
              <td v-if="i === 1" colspan="2">
                <div class="span-cell">
                  与气体、蒸汽质量计算相关的温度计算
                </div>
              </td>
              <td
                v-for="(d, index) in item.data"
                :key="`${item.uuid}_${index}`"
              >
                <div v-if="!d.editable" class="span-cell">
                  {{ d.value }}
                </div>
                <div v-else class="input-cell">
                  <input
                    v-model="d.value"
                    type="text"
                    @click="clickCallback"
                  >
                </div>
              </td>
            </tr>

            <!-- 压力仪表 -->
            <tr
              v-for="(item, i) in lists7"
              :key="item.uuid"
            >
              <td
                v-if="i === 0"
                :rowspan="lists7.length"
                class="no-border-bottom"
              >
                <div class="span-cell">
                  压力仪表
                </div>
              </td>
              <td v-if="i === 0" colspan="2">
                <div class="span-cell">
                  用于液态、气态能源的压力计算
                </div>
              </td>
              <td v-if="i === 1" colspan="2">
                <div class="span-cell">
                  与气体、蒸汽质量计算相关的压力计算
                </div>
              </td>
              <td
                v-for="(d, index) in item.data"
                :key="`${item.uuid}_${index}`"
              >
                <div v-if="!d.editable" class="span-cell">
                  {{ d.value }}
                </div>
                <div v-else class="input-cell">
                  <input
                    v-model="d.value"
                    type="text"
                    @click="clickCallback"
                  >
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </ElScrollbar>
      <ReportPerson
        v-model="informant"
        :readonly="readonly"
      />
    </div>
  </WrapComponent>
</template>
